package agent

import (
	"time"

	"gitee.com/shiwjlinux/arm/apps/instance"
)

func (a *InstanceAgent) runHeartbeatLoop() {
	ticker := time.NewTicker(heartbeatTicker)
	defer ticker.Stop()

	for {
		select {
		case <-ticker.C:
			// if err := a.sendHeartbeat(); err != nil {
			if err := a.sendHeartbeats(); err != nil {
				a.logger.Error().Err(err).Msg("failed to send heartbeat")
			}
		case <-a.stopChan:
			return
		case <-a.ctx.Done():
			return
		}
	}
}

// 发送心跳
func (a *InstanceAgent) sendHeartbeat() error {
	// 实例id 怎么获取
	for id := range a.Instance {
		req := instance.NewUpdateHeartbeatRequest(id)
		req.UpdatedAt = time.Now().Unix() // 获取客户端当前的时间
		_, err := a.client.UpdateHeartbeat(ctx, req)
		if err != nil {
			a.logger.Error().Err(err).Str("id", id).Msg("failed to update instance heartbeat")
		}

		a.logger.Info().Str("id", id).Msg("update instance heartbeat successfully")

	}
	return nil
}

func (a *InstanceAgent) sendHeartbeats() error {
	var ids []string
	for id := range a.Instance {
		ids = append(ids, id)
	}

	req := instance.NewUpdateHeartbeatRequests(ids)
	req.UpdatedAt = time.Now().Unix() // 获取客户端当前的时间
	err := a.client.UpdateHeartbeats(ctx, req)
	if err != nil {
		a.logger.Error().Err(err).Strs("ids=", ids).Msg("failed to update instance heartbeat")
		return err
	}

	a.logger.Info().Strs("ids", ids).Msg("update instance heartbeat successfully")
	return nil
}
